package com.newly.center.sys.api;

import cn.hutool.core.bean.BeanUtil;
import com.newly.api.sys.feign.DeviceClient;
import com.newly.center.sys.service.device.impl.DeviceService;
import com.newly.common.base.constants.CodeConstant;
import com.newly.common.base.constants.ServerUriConstant;
import com.newly.common.base.entity.R;
import com.newly.common.base.entity.device.dto.DeviceDto;
import com.newly.common.base.entity.device.vo.DeviceMonitorVo;
import com.newly.common.base.entity.device.vo.ExcelDeviceMonitor;
import com.newly.common.base.exception.NewlyException;
import com.newly.common.core.utils.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @anthor sbq
 * @date 2021/11/25 9:58
 */
@RestController
@RequestMapping(ServerUriConstant.NEWLY_SYS_DEVICE)
public class DeviceController implements DeviceClient {

    @Autowired
    private DeviceService deviceService;

    @Override
    public void export(HttpServletResponse response, DeviceDto deviceDto) {
        deviceDto.setPageSize(1);
        int totalCount = deviceService.monitor(deviceDto).getTotalCount();
        if (totalCount < 1) {
            throw new NewlyException(CodeConstant.SUCCESS, "无数据");
        }
        deviceDto.setPageSize(totalCount);
        List<DeviceMonitorVo> list = (List<DeviceMonitorVo>) deviceService.monitor(deviceDto).getList();

        List<ExcelDeviceMonitor> collect = list.stream().map(v -> {
            String[] ignoreProperties = new String[]{"siteStatus", "weighingStatus", "snapStatus"};
            ExcelDeviceMonitor excel = BeanUtil.copyProperties(v, ExcelDeviceMonitor.class, ignoreProperties);
            Integer siteStatus = v.getSiteStatus();
            Integer weighingStatus = v.getWeighingStatus();
            Integer snapStatus = v.getSnapStatus();
            excel.setSiteStatus(siteStatus == null ? "" : (siteStatus == 0 ? "正常" : "异常"))
                    .setWeighingStatus(weighingStatus == null ? "" : (weighingStatus == 0 ? "在线" : "离线"))
                    .setSnapStatus(snapStatus == null ? "" : (snapStatus == 0 ? "在线" : "离线"));
            return excel;
        }).collect(Collectors.toList());

        ExcelUtil.export(response, "设备监控表", null, collect, ExcelDeviceMonitor.class);
    }

    @Override
    public R getNames() {

        return R.ok(this.deviceService.getNames());
    }

    @Override
    public R monitor(DeviceDto deviceDto) {

        return R.ok(this.deviceService.monitor(deviceDto));
    }
}
